<template>
  <QfPage title="赛事管理">
    <template #hd>
      <a-row>
        <a-col :span="2">
          <!-- 添加按钮 -->
          <a-button @click="showAddModal = true">添加</a-button>
        </a-col>
        <a-col :span="12">
          <!-- 赛事名称搜索 -->
          <a-input-search
            v-model:value="eventName"
            placeholder="输入赛事名称"
            style="width: 200px"
            @search="onSearch"
          />
        </a-col>
      </a-row>
    </template>
    <a-table :dataSource="dataSource" :columns="columns" :pagination="false">
      <template #bodyCell="{ record, column }">
        <!-- 判断如何是 key等于 action的时候 就按照下面的模板的内容来显示 -->
        <template v-if="column.key === 'action'">
          <a-button @click="handleEdit(record)">编辑</a-button>
          <a-button @click="handleDel(record.id)">删除</a-button>
        </template>
      </template>
    </a-table>

    <!-- 分页的操作 -->
    <template #ft>
      <a-pagination
        v-model:current="page"
        :defaultPageSize="limit"
        :total="total"
        show-less-items
        @change="onPageChange"
      />
    </template>

    <!-- 添加弹窗 -->
    <a-modal :width="650" v-model:visible="showAddModal" title="添加赛事">
      <a-form :model="newEvent" ref="addForm" class="myform" :rules="rules">
        <a-steps class="mystep" :current="curStep" size="small">
          <a-step title="基本信息" />
          <a-step title="时间" />
          <a-step title="报名内容" />
          <a-step title="奖励规则" />
        </a-steps>
        <!-- 第一步要填写的表单内容 -->
        <div v-show="curStep === 0">
          <a-form-item label="赛事名称" name="name">
            <a-input v-model:value="newEvent.name" />
          </a-form-item>
          <a-form-item label="参赛人数" name="peopleLimit">
            <a-input v-model:value="newEvent.peopleLimit" />
          </a-form-item>
          <a-form-item label="起始资金" name="startMoney">
            <a-input v-model:value="newEvent.startMoney" />
          </a-form-item>
          <a-form-item label="赛事封面">
            <el-upload
              v-model:file-list="fileList"
              class="upload-demo"
              :limit="1"
              :http-request="handleUploadOk"
            >
              <el-button type="primary">Click to upload</el-button>
              <template #tip>
                <div class="el-upload__tip">jpg/png files with a size less than 500KB.</div>
              </template>
            </el-upload>
          </a-form-item>
          <a-form-item label="赛事描述">
            <QuillEditor
              contentType="html"
              v-model:content="newEvent.desc"
              class="myeditor"
              theme="snow"
            />
          </a-form-item>
        </div>
        <!-- 第2步要填写的表单内容 -->
        <div v-show="curStep === 1">
          <a-form-item label="报名时间" :rules="dateRules" name="enrollRange">
            <a-range-picker v-model:value="newEvent.enrollRange" :locale="locale" />
          </a-form-item>
          <a-form-item label="比赛时间" name="eventRange" :rules="dateRules">
            <a-range-picker v-model:value="newEvent.eventRange" :locale="locale" />
          </a-form-item>
        </div>
        <!-- 自定义表单 第三步 -->
        <div v-show="curStep == 2">
          <div>
            <a-row>
              <a-col :span="4">表单的label</a-col>
              <a-col :span="6"> 输入提示</a-col>
              <a-col :span="4"> 变量名</a-col>
              <a-col :span="6"> 类型</a-col>
              <a-col :span="4"> 类型</a-col>
            </a-row>
            <a-row v-for="(item, index) of cusForm" :key="index">
              <a-col :span="4">
                <a-input v-model:value="cusForm[index].label" />
              </a-col>
              <a-col :span="4">
                <a-input v-model:value="cusForm[index].placeholder" />
              </a-col>
              <a-col :span="4">
                <a-input v-model:value="cusForm[index].varname" />
              </a-col>
              <a-col :span="6">
                <a-select v-model:value="cusForm[index].type" style="width: 120px">
                  <a-select-option value="text">输入框</a-select-option>
                  <a-select-option value="date">日期</a-select-option>
                  <a-select-option value="radio">单选框</a-select-option>
                </a-select>
              </a-col>
              <a-col :span="4" v-show="cusForm[index].type === 'radio'">
                <a-popover v-model:visible="visible" title="子选项" trigger="click">
                  <template #content>
                    <div class="it" v-for="(it, idx) of cusForm[index].options" :key="idx">
                      选项 {{ idx + 1 }}:
                      <a-input v-model:value="cusForm[index].options[idx]" />
                    </div>
                    <button @click="cusForm[index].options.push('')">添加</button>
                  </template>
                  <a-button type="primary">子选项</a-button>
                </a-popover>
              </a-col>
            </a-row>
            <button
              @click="
                cusForm.push({
                  label: '',
                  placeholder: '',
                  varname: '',
                  type: '',
                  options: [],
                })
              "
            >
              添加表单项
            </button>
          </div>
          <button @click="showCusForm">打印这个规则</button>
        </div>

        <div v-show="curStep === 3">
          <div>
            <button @click="jfList.push(0)">添加名次</button>
            <a-input v-model:value="rangCount" placeholder="奖励前xx名" />
            <button @click="addRangByCount">确认添加</button>
            <a-form-item
              :label="`第${index + 1}名奖励的积分`"
              v-for="(item, index) of jfList"
              :key="index"
            >
              <a-input v-model:value="jfList[index]" />
            </a-form-item>
          </div>
        </div>
      </a-form>
      <template #footer>
        <button v-show="curStep > 0" @click="curStep--">上一步</button>
        <button v-show="curStep !== 3" @click="curStep++">下一步</button>
        <button v-show="curStep === 3" @click="handleAdd">提交</button>
        <button @click="test">手动的校验表单</button>
      </template>
    </a-modal>

    <!-- 编辑的抽屉 -->
    <a-drawer :width="850" v-model:visible="showEdit">
      <a-form :model="editEvent" ref="editForm" class="myform" :rules="editRules">
        <a-form-item label="赛事名称" name="name">
          <a-input v-model:value="editEvent.name" />
        </a-form-item>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="参赛人数" name="peopleLimit">
              <a-input v-model:value="editEvent.peopleLimit" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="起始资金" name="startMoney">
              <a-input v-model:value="editEvent.startMoney" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="报名时间" :rules="editDateRules" name="enrollRange">
              <a-range-picker v-model:value="editEvent.enrollRange" :locale="locale" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="比赛时间" name="eventRange" :rules="editDateRules">
              <a-range-picker v-model:value="editEvent.eventRange" :locale="locale" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="赛事描述">
          <QuillEditor
            contentType="html"
            v-model:content="editEvent.desc"
            class="myeditor"
            theme="snow"
          />
        </a-form-item>

        <button @click="eidtJfList.push(0)">添加名次</button>

        <a-form-item
          :label="`第${index + 1}名奖励的积分`"
          v-for="(item, index) of eidtJfList"
          :key="index"
        >
          <a-input v-model:value="eidtJfList[index]" />
        </a-form-item>
      </a-form>
      <a-button @click="confirmUpdate">确认修改</a-button>
      <a-button @click="showEdit = false">取消</a-button>
    </a-drawer>
  </QfPage>
</template>

<script>
import { defineComponent } from 'vue';
import _ from 'lodash';
import dayjs from 'dayjs';
import { message, Modal } from 'ant-design-vue';
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import EventApi from '@/api/event';
// eslint-disable-next-line import/no-unresolved
import { put, getFileNameUUID } from '@/utils/alioss';

export default defineComponent({
  data() {
    return {
      cusForm: [
        {
          label: '',
          placeholder: '',
          varname: '',
          type: '',
          options: [],
        },
      ],
      showEdit: false,
      page: 1,
      total: 0,
      limit: 5,
      eventName: '',
      locale,
      // 添加表单的校验规则
      // 在form表单上面的规则
      rules: {
        // required: true 表示必填
        // message:  不符合条件的时候的提示信息
        // trigger:  触发校验的时机
        name: [{ required: true, message: '请输入赛事名称', trigger: 'blur' }],
        peopleLimit: [{ required: true, message: '请输入参赛人数', trigger: 'blur' }],
        startMoney: [
          // { required: true, message: '请输入起始资金', trigger: 'blur' },
          { trigger: 'blur', validator: this.checkMoney },
        ],
      },
      editRules: {
        name: [{ required: true, message: '请输入赛事名称', trigger: 'blur' }],
        peopleLimit: [{ required: true, message: '请输入参赛人数', trigger: 'blur' }],
        startMoney: [{ trigger: 'blur', validator: this.checkEditMoney }],
      },

      dateRules: [
        {
          type: 'array',
          validator: this.checkDate,
          message: '比赛事件不能早于报名的截止时间',
          trigger: 'change',
        },
      ],
      editDateRules: [
        {
          type: 'array',
          validator: this.checkEditDate,
          message: '比赛事件不能早于报名的截止时间',
          trigger: 'change',
        },
      ],
      dataSource: [],
      columns: [
        {
          title: 'id', // 表头文字内容
          dataIndex: 'id',
          key: 'id',
        },
        {
          title: '赛事名称',
          dataIndex: 'name',
          key: 'name',
        },
        {
          title: '参赛人数',
          dataIndex: 'peopleLimit',
          key: 'peopleLimit',
        },
        {
          title: '起始资金',
          dataIndex: 'startMoney',
          key: 'startMoney',
        },
        {
          title: '报名时间',
          key: 'enrollRange',
          customRender({ record }) {
            const s = dayjs(record.enrollStime).format('YYYY-MM-DD');
            const e = dayjs(record.enrollEtime).format('YYYY-MM-DD');
            return `${s} ~ ${e}`;
          },
        },
        {
          title: '比赛时间',
          key: 'enrollRange',
          customRender({ record }) {
            const s = dayjs(record.stime).format('YYYY-MM-DD');
            const e = dayjs(record.etime).format('YYYY-MM-DD');
            return `${s} ~ ${e}`;
          },
        },
        {
          title: '操作',
          key: 'action',
        },
      ],
      rangCount: '',
      showAddModal: false,
      curStep: 0,
      jfList: [], // 新增的时候的积分奖励列表
      eidtJfList: [], // 编辑的时候的积分奖励列表
      newEvent: {
        name: '',
        peopleLimit: '',
        desc: '',
        startMoney: '',
        enrollRange: [],
        eventRange: [],
      },
      editEvent: {
        name: '',
        peopleLimit: '',
        desc: '',
        startMoney: '',
        enrollRange: [],
        eventRange: [],
      },
      curId: null,
      fileList: [],
    };
  },
  created() {
    this.getData();
  },
  watch: {
    page(nv) {
      console.log('页码的值', nv);
    },
    fileList(nv) {
      console.log('nv', nv);
    },
  },
  methods: {
    async multUploadOk(option) {
      console.log('点击上传要得到的内容', option);
    },
    async handleUploadOk(option) {
      console.log('点击上传要得到的内容', option);
      // 我们无论是使用什么ui框架 上传的流程当中只要能获取到 文件的file对象就可以完成自定义的上传
      // 生成的文件名称
      // 电竞平台.png => split => [电竞平台, png] => pop => png
      const objName = [getFileNameUUID(), option.file.name.split('.').pop()].join('.');

      // 调用 ali-oss 中的方法  put(文件名, 文件对象)
      const res = await put(`${objName}`, option.file);
      console.log('上传的结果', res);
      // 对于elemetui或者是plus 自定义上传成功之后需要正确的填充上传的结果到 fileList
      // 这里需要手动的通过 Promise.resolve来返回请求的结果 这个结果会自动的加载到
      return Promise.resolve({
        name: objName,
        url: `http://static.qf2208henduoqian.vip/${objName}`,
      });
    },
    // 临时的查看自定义表单的规则
    showCusForm() {
      console.log('组定义表单', this.cusForm);
    },
    // 处理删除的操作
    async handleDel(id) {
      console.log('id', id);
      // 提醒用户进行删除的二次确认
      Modal.confirm({
        title: '删除赛事',
        content: '确定了？不后悔？一次机会都不给了？？？',
        onOk: async () => {
          const res = await EventApi.delEvent(id);
          console.log('删除的结果 ', res);
          const { status } = res;
          if (status !== 200) return message.warning('删除失败');
          message.success('删除成功');
          return this.getData();
        },
        onCancel() {
          console.log('Cancel');
        },
        class: 'test',
      });
    },
    // 处理分页页码变化
    onPageChange(page) {
      this.page = page;
      this.getData();
    },
    // 搜索 根据赛事名称
    onSearch() {
      this.page = 1;
      this.getData();
    },
    test() {
      console.log('校验的结果');
      this.$refs.addForm
        .validate()
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log('err', err);
        });
    },
    async checkDate() {
      // 如果有了比赛时间和报名时间 比赛时间不能早于报名的截止时间
      const enrollEtime = this.newEvent.enrollRange[1];
      const eventStime = this.newEvent.eventRange[0];
      if (enrollEtime && eventStime) {
        if (enrollEtime.isAfter(eventStime)) {
          // 如果报名截止事件晚于比赛开始时间
          return Promise.reject('比赛时间不能早于报名的截止时间');
        }
      }
      return Promise.resolve();
    },
    async checkEditDate() {
      // 如果有了比赛时间和报名时间 比赛时间不能早于报名的截止时间
      const enrollEtime = this.editEvent.enrollRange[1];
      const eventStime = this.editEvent.eventRange[0];
      if (enrollEtime && eventStime) {
        if (enrollEtime.isAfter(eventStime)) {
          // 如果报名截止事件晚于比赛开始时间
          return Promise.reject('比赛时间不能早于报名的截止时间');
        }
      }
      return Promise.resolve();
    },
    checkMoney() {
      const { startMoney } = this.newEvent;
      if (startMoney < 100) {
        return Promise.reject('起始资金不能小于100');
      }
      return Promise.resolve();
    },
    checkEditMoney() {
      const { startMoney } = this.editEvent;
      if (startMoney < 100) {
        return Promise.reject('起始资金不能小于100');
      }
      return Promise.resolve();
    },
    // 执行修改
    async confirmUpdate() {
      this.$refs.editForm
        .validate()
        .then(async (result) => {
          // 表单校验成功
          // 第一个表单的数据
          const { enrollRange, eventRange, ...rest } = this.editEvent;
          const postData = {
            ...rest,
          };

          // 报名时间;
          const [enrollStime, enrollEtime] = this.editEvent.enrollRange;
          postData.enrollStime = enrollStime.$d;
          postData.enrollEtime = enrollEtime.$d;

          // 比赛时间
          const [sTime, eTime] = this.editEvent.eventRange;
          postData.stime = sTime.$d;
          postData.etime = eTime.$d;
          postData.jf = JSON.stringify(this.eidtJfList);

          // 开始可以执行ajax要求
          const res = await EventApi.editEvent(this.curId, postData);
          console.log('添加的结果是', res);
          const { status } = res;
          if (status !== 200) return message.warning('编辑失败');
          message.success('编辑成功');
          this.showEdit = false;
          this.getData();
          return false;
        })
        .catch((err) => {
          // 表单校验失败
          console.log('err', err);
          message.warning('请检查表单');
        });

      return false;
    },
    // 执行添加
    async handleAdd() {
      // 先进行表单校验

      this.$refs.addForm
        .validate()
        .then(async (result) => {
          // 表单校验成功
          // 第一个表单的数据
          console.log('newEvent', this.newEvent);
          const { enrollRange, eventRange, ...rest } = this.newEvent;
          const postData = {
            ...rest,
          };

          // 报名时间;
          const [enrollStime, enrollEtime] = this.newEvent.enrollRange;
          postData.enrollStime = enrollStime.$d;
          postData.enrollEtime = enrollEtime.$d;

          // 比赛时间
          const [sTime, eTime] = this.newEvent.eventRange;
          postData.stime = sTime.$d;
          postData.etime = eTime.$d;
          postData.jf = JSON.stringify(this.jfList);

          // 添加自定义表单
          postData.cusForm = JSON.stringify(this.cusForm);
          // 添加封面图的图片访问链接
          postData.cover = this.fileList[0].response.url;

          // 开始可以执行ajax要求
          const res = await EventApi.addEvent(postData);

          const { status } = res;
          if (status !== 201) return message.warning('添加失败');
          message.success('添加成功');
          this.showAddModal = false;
          return false;
        })
        .catch((err) => {
          // 表单校验失败
          console.log('err', err);
          message.warning('请检查表单');
        });

      return false;
    },
    async getData() {
      const res = await EventApi.getEventList({
        keyword: this.eventName,
        $limit: this.limit,
        $page: this.page,
      });
      console.log('res', res);
      const { status, data } = res;
      // 在请求成功得到内容之后 修改表格的数据源
      if (status === 200) {
        this.dataSource = data.data;
        this.total = data.total;
      }
    },
    handleEdit(record) {
      this.curId = record.id; // 标记要修改的信息的id
      this.showEdit = true; // 弹出抽屉
      this.editEvent = _.cloneDeep(record); // 建议使用深拷贝
      this.editEvent.enrollRange = [
        dayjs(this.editEvent.enrollStime),
        dayjs(this.editEvent.enrollEtime),
      ];
      this.editEvent.eventRange = [dayjs(this.editEvent.stime), dayjs(this.editEvent.etime)];
      this.eidtJfList = JSON.parse(this.editEvent.jf);
      console.log('积分奖励列表', this.eidtJfList);
    },

    addRangByCount() {
      this.jfList = [];
      const count = Number(this.rangCount);
      for (let i = 0; i < count; i += 1) {
        this.jfList.push(0);
      }
    },
  },
});
</script>

<style scoped lang="scss">
.mystep {
  margin-bottom: 20px;
}
// 如果需要修改子组件里面的样式 直接书写没有效果的话怎么办？？？？
//   :deep  ::v-deep  /deep/  >>>
:deep .myeditor {
  height: 400px;
}

.it {
  width: 252px;
  display: flex;
}
</style>
